import request from '@/utils/request';
import type { Customer, CustomerQuery, CustomerLog } from '@/types/customer';
import type { PageResponse } from '@/types/common';

export interface ApproveRequest {
  approved: boolean
  comment: string
}

export interface CustomerDepartment {
  id: number
  customerId: number
  departmentId: number
  departmentName: string
  salesId: number
  salesName: string
}

export interface Department {
  id: number
  name: string
}

export interface Sales {
  id: number
  name: string
}

export const getCustomers = (params: CustomerQuery) => {
  return request.get<PageResponse<Customer>>('/api/customers', { params });
};

export const getCustomer = (id: number) => {
  return request.get<Customer>(`/api/customers/${id}`);
};

export const createCustomer = (data: Partial<Customer>) => {
  return request.post<Customer>('/api/customers', data);
};

export const updateCustomer = (id: number, data: Partial<Customer>) => {
  return request.put<Customer>(`/api/customers/${id}`, data);
};

export const deleteCustomer = (id: number) => {
  return request.delete(`/api/customers/${id}`);
};

export const approveCustomer = (id: number, data: { approved: boolean; comment: string }) => {
  return request.put<Customer>(`/api/customers/${id}/approve`, data);
};

// 获取客户关联的部门
export const getCustomerDepartments = (customerId: number) => {
  return request.get<CustomerDepartment[]>(`/api/customers/${customerId}/departments`);
};

// 添加客户部门关联
export const addCustomerDepartment = (customerId: number, data: { departmentId: number; salesId: number }) => {
  return request.post(`/api/customers/${customerId}/departments`, data);
};

// 删除客户部门关联
export const deleteCustomerDepartment = (customerId: number, departmentId: number) => {
  return request.delete(`/api/customers/${customerId}/departments/${departmentId}`);
};

// 获取所有部门
export const getAllDepartments = () => {
  return request.get<Department[]>('/api/customer-departments');
};

// 获取所有销售
export const getAllSales = (name?: string) => {
  return request.get<Sales[]>('/api/sales', { params: { name } });
};

export function searchCustomers(query: string) {
  return request({
    url: '/api/customers/search',
    method: 'get',
    params: { query }
  })
}

// 客户日志相关API
export const getCustomerLogs = (customerId: number) => {
  return request.get<CustomerLog[]>(`/api/customer-logs/customer/${customerId}`)
}

export const getOperatorLogs = (operatorId: number) => {
  return request.get<CustomerLog[]>(`/api/customer-logs/operator/${operatorId}`)
}

export const getMyCustomerLogs = () => {
  return request.get<CustomerLog[]>('/api/customer-logs/my')
}
